﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FastPoster.MainForms
{
    #region using
    using DevComponents.DotNetBar;
    using FastPoster.DataProviders.BUS;
    using FastPoster.Helpers;
    using System.Diagnostics;
    using FastPoster.DataProviders.DTO;
    using FastPoster.MainClasses;
    using Amib.Threading;
    using System.Threading;
    using System.Threading.Tasks;
    #endregion

    public partial class FrmXemCacBaiVietDaDang : Office2007Form
    {
        private bool                    bnLoading;
        private List<BaiVietDaDangDTO>  lstBaiVietDaDang;
        private int                     currPoster;
        private BackgroundWorker        PostingBackgroundWorker;

        public void InitChecking()
        {
            currPoster = 0;
            progBarKetQuaDangTin.Value = 0;
            btnLoaiBo.Enabled = false;
            dtgvBaiVietKhongCon.Rows.Clear();
        }

        public FrmXemCacBaiVietDaDang()
        {
            InitializeComponent();
            InitChecking();
            InitWorker();
        }

        /// <summary>
        /// Init background worker
        /// </summary>
        private void InitWorker()
        {
            PostingBackgroundWorker = new BackgroundWorker();
            PostingBackgroundWorker.WorkerReportsProgress = true;
            PostingBackgroundWorker.WorkerSupportsCancellation = true;

            PostingBackgroundWorker.DoWork += PostingBackgroundWorker_DoWork;
            PostingBackgroundWorker.ProgressChanged += PostingBackgroundWorker_ProgressChanged;
            PostingBackgroundWorker.RunWorkerCompleted += PostingBackgroundWorker_RunWorkerCompleted;
        }

        public void DoCheck(Poster poster, int index)
        {
            try
            {
                if (PostingBackgroundWorker.CancellationPending)
                {
                    return;
                }

                Task.Factory.StartNew(() => poster.CheckingBoxDied(index));
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    GlobalVariables.Logger.Error("DoCheck: failed - error: " + ex.InnerException.Message);
                }
                else
                {
                    GlobalVariables.Logger.Error("DoCheck: failed - error: " + ex.Message);
                }
            }
        }

        /// <summary>
        /// This method is executed when RunWorkerAsync is called.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PostingBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            GlobalVariables.Logger.Info("Checking: started");
            try
            {
                for (int i = 0; i < lstBaiVietDaDang.Count; i++)
                {
                    Poster poster = new Poster
                    {
                        IDBaiVietDaDang = lstBaiVietDaDang[i].ID,
                        Url = lstBaiVietDaDang[i].URL,
                        NgayDang = lstBaiVietDaDang[i].NgayDang
                    };
                    poster.ProgressChanged += OnPosterProgressChanged;

                    DoCheck(poster, i);
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    GlobalVariables.Logger.Error("Checking: failed - error: " + ex.InnerException.Message);
                }
                else
                {
                    GlobalVariables.Logger.Error("Checking: failed - error: " + ex.Message);
                }
            }
        }

        private void PostingBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (!PostingBackgroundWorker.CancellationPending)
            {
                progBarKetQuaDangTin.PerformStep();
            }
        }

        private void PostingBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnLoaiBo.Enabled = true;
        }

        public void LoadBaiVietMaus()
        {
            var objBus = new BaiVietMauBUS(GlobalVariables.g_strPath);
            var ds = objBus.SelectAll();
            cbxTieuDeBaiViet.DataSource = ds.Tables[0];
            cbxTieuDeBaiViet.DisplayMember = "TieuDe";
            cbxTieuDeBaiViet.ValueMember = "ID";
            cbxTieuDeBaiViet.SelectedIndex = -1;

            cbxBaiVietKhongCon.DataSource = ds.Tables[0];
            cbxBaiVietKhongCon.DisplayMember = "TieuDe";
            cbxBaiVietKhongCon.ValueMember = "ID";
            cbxBaiVietKhongCon.SelectedIndex = -1;
        }

        private void FrmXemCacBaiVietDaDang_Load(object sender, EventArgs e)
        {
            bnLoading = true;
            LoadBaiVietMaus();
            bnLoading = false;
        }

        private void cbxTieuDeBaiViet_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (bnLoading)
            {
                return;
            }
            if (cbxTieuDeBaiViet.SelectedIndex != -1)
            {
                var objBus = new BaiVietDaDangBUS(GlobalVariables.g_strPath);
                var ds = objBus.SelectByIDBaiVietMau(int.Parse(cbxTieuDeBaiViet.SelectedValue.ToString()));
                if (ds.Tables[0].Rows.Count > 0)
                {
                    dtgvBaiVietDaDang.Rows.Clear();
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        dtgvBaiVietDaDang.Rows.Add(dtgvBaiVietDaDang.Rows.Count + 1, row["URL"].ToString(), row["NgayDang"].ToString());
                    }
                }
            }
        }

        private void dtgvBaiVietDaDang_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (((e.RowIndex >= 0) && (dtgvBaiVietDaDang.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)) && ((e.ColumnIndex == 1)))
            {
                Process.Start(dtgvBaiVietDaDang.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            }
        }

        private void btnKiemTra_Click(object sender, EventArgs e)
        {
            if (cbxBaiVietKhongCon.SelectedIndex == -1)
            {
                MessageBoxEx.Show("Vui lòng chọn bài viết", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            InitChecking();

            // Init other controls
            progBarKetQuaDangTin.Minimum = 0;
            progBarKetQuaDangTin.Maximum = lstBaiVietDaDang.Count;
            progBarKetQuaDangTin.Step = 1;
            progBarKetQuaDangTin.Value = 0;

            // Activate checking
            if (PostingBackgroundWorker.IsBusy)
            {
                PostingBackgroundWorker.CancelAsync();
            }
            else
            {
                progBarKetQuaDangTin.Value = progBarKetQuaDangTin.Minimum;
                PostingBackgroundWorker.RunWorkerAsync();
            }
        }

        private void cbxBaiVietKhongCon_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (bnLoading)
            {
                return;
            }
            if (cbxBaiVietKhongCon.SelectedIndex != -1)
            {
                var objBus = new BaiVietDaDangBUS(GlobalVariables.g_strPath);
                var ds = objBus.SelectByIDBaiVietMau(int.Parse(cbxBaiVietKhongCon.SelectedValue.ToString()));
                if (ds.Tables[0].Rows.Count > 0)
                {
                    lstBaiVietDaDang = new List<BaiVietDaDangDTO>();
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        var baivietdadang = new BaiVietDaDangDTO
                        {
                            ID =  int.Parse(row["ID"].ToString()),
                            IDBaiVietMau = int.Parse(row["IDBaiVietMau"].ToString()),
                            IDBox = int.Parse(row["IDBaiVietMau"].ToString()),
                            URL = row["URL"].ToString(),
                            NgayDang = DateTime.Parse(row["NgayDang"].ToString()),
                        };
                        lstBaiVietDaDang.Add(baivietdadang);
                    }
                }
            }
        }

        private void OnPosterProgressChanged(object sender, EventArgs e)
        {
            var eventType = (ProgressChangedArgs)e;
            MethodInvoker method = null;
            if (base.InvokeRequired)
            {
                if (method == null)
                {
                    method = delegate
                    {
                        this.OnPosterProgressChanged(sender, e);
                    };
                }
                base.BeginInvoke(method);
            }
            else
            {
                Poster poster = (Poster)sender;
                if (poster.IsDeadBox)
                {
                    dtgvBaiVietKhongCon.Rows.Add(dtgvBaiVietKhongCon.Rows.Count + 1, poster.IDBaiVietDaDang.ToString(), poster.Url, poster.NgayDang.ToString("G"));
                }
                currPoster++;
                PostingBackgroundWorker.ReportProgress(currPoster >= lstBaiVietDaDang.Count ? 100 : (int)(currPoster / lstBaiVietDaDang.Count * 100));
            }
        }

        private void dtgvBaiVietKhongCon_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (((e.RowIndex >= 0) && (dtgvBaiVietKhongCon.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)) && ((e.ColumnIndex == 2)))
            {
                Process.Start(dtgvBaiVietKhongCon.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            }
        }

        private void btnLoaiBo_Click(object sender, EventArgs e)
        {
            GlobalVariables.PreLoading();

            for (int i = 0; i < dtgvBaiVietKhongCon.Rows.Count; i++)
            {
                var objBus = new BaiVietDaDangBUS(GlobalVariables.g_strPath);
                if (objBus.Delete(int.Parse(dtgvBaiVietKhongCon.Rows[i].Cells[1].Value.ToString())))
                {
                    GlobalVariables.Logger.Info("Loai bo " + dtgvBaiVietKhongCon.Rows[i].Cells[2].Value.ToString() + ": done");
                }
                else
                {
                    GlobalVariables.Logger.Info("Loai bo " + dtgvBaiVietKhongCon.Rows[i].Cells[2].Value.ToString() + ": failed");
                }
            }

            GlobalVariables.PosLoading();
            MessageBoxEx.Show("Hoàn tất việc loại bỏ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
